<template>
  <view class="company-detail-page">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="goBack" hover-class="back-btn-hover">
        <u-icon name="arrow-left" size="36" color="#333"></u-icon>
      </view>
      <text class="nav-title">公司详情</text>
      <view class="nav-right"></view> <!-- 占位元素，使标题居中 -->
    </view>

    <!-- 公司头部信息卡片 -->
    <view class="company-header-card">
      <view class="company-header-content">
        <image 
          class="company-logo" 
          :src="company.image || '/static/company-building.png'" 
          mode="aspectFill"
          lazy-load
        ></image>
        
        <view class="company-basic-info">
          <text class="company-name">{{ company.name || '未知公司' }}</text>
          
          <view class="company-meta">
            <text class="meta-item" v-if="company.scale">{{ company.scale }}</text>
            <text class="meta-divider" v-if="company.scale && company.companyType">|</text>
            <text class="meta-item" v-if="company.companyType">{{ company.companyType }}</text>
          </view>
          
          <!-- 地址区域：导航按钮 -->
          <view class="company-address-wrapper">
            <u-icon name="map-marker" size="24" color="#666" class="address-icon"></u-icon>
            <text class="company-address">{{ company.address || '暂无地址信息' }}</text>
            <!-- 高德导航按钮：仅经纬度有效时显示 -->
            <view 
              v-if="isLocationValid"
              class="navigate-btn"
              @click="openGaodeMap"
              hover-class="navigate-btn-hover"
            >
              <u-icon name="map" size="24" color="#409eff"></u-icon>
              <text class="navigate-text">导航</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 公司人事 -->
    <view class="info-card">
      <view class="card-header">
        <text class="card-title">招聘联系人</text>
        <u-icon name="people" size="28" color="#409eff"></u-icon>
      </view>
      
      <view class="card-content">
        <view class="hr-list" v-if="company.hrList && company.hrList.length > 0">
          <view class="hr-item" v-for="(hr, idx) in company.hrList" :key="idx">
            <image 
              class="hr-avatar" 
              src="/static/avatar/avatar.png" 
              mode="aspectFill"
              lazy-load
            ></image>
            <view class="hr-info">
              <text class="hr-name">{{ hr.hrName || '未知姓名' }}</text>
              <text class="hr-position">{{ hr.identity === 0 ? "人事主管" : "人事" }}</text>
            </view>
          </view>
        </view>
        
        <view class="empty-state" v-else>
          <u-icon name="empty" size="60" color="#ccc"></u-icon>
          <text class="empty-text">暂无人事信息</text>
        </view>
      </view>
    </view>

    <!-- 工商信息 -->
    <view class="info-card">
      <view class="card-header">
        <text class="card-title">工商信息</text>
        <u-icon name="document" size="28" color="#409eff"></u-icon>
      </view>
      
      <view class="card-content">
        <view class="business-info-grid">
          <view class="business-info-item" v-for="(val, key) in company.businessInfo" :key="key">
            <text class="info-label">{{ key }}：</text>
            <text class="info-value">{{ val || '暂无数据' }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCompanyInfoByCompanyId } from '@/api/user.js'
export default {
  data() {
    return {
      userId: null,
      companyId: null,
      company: {
        companyId: null,
        companyType: '',
        name: '',
        scale: '',
        image: '',
        address: '',
        hrList: [],
        businessInfo: {
          '公司全称': '',
          '法定代表人': '',
          '成立日期': '',
          '统一社会信用代码': '',
        },
        locationInfo: { // 经纬度信息
          latitude: null,
          longitude: null
        }
      }
    }
  },
  computed: {
    // 计算属性：判断经纬度是否有效
    isLocationValid() {
      const { latitude, longitude } = this.company.locationInfo;
      return latitude !== null && longitude !== null 
        && !isNaN(Number(latitude)) && !isNaN(Number(longitude))
        && latitude >= -90 && latitude <= 90 
        && longitude >= -180 && longitude <= 180;
    }
  },
  onLoad(val) {
    this.userId = val.userId;
    this.companyId = val.companyId;
    this.loadCompanyInfo();
  },
  methods: {
    // 加载公司信息（含经纬度拆分处理）
    loadCompanyInfo() {
      uni.showLoading({ title: '加载中...' });
      
      getCompanyInfoByCompanyId({ companyId: this.companyId })
        .then(res => {
          const data = res.data || {};
          let latitude = null;
          let longitude = null;
          // 处理经纬度拆分（从locationInfo提取）
          if (data.locationInfo && typeof data.locationInfo === 'string' && data.locationInfo.trim() !== '') {
            const locationSplit = data.locationInfo.trim().split("%#&");
            if (locationSplit.length === 2) {
              const latStr = locationSplit[0].trim();
              const lonStr = locationSplit[1].trim();
              if (!isNaN(Number(latStr)) && !isNaN(Number(lonStr))) {
                latitude = Number(latStr);
                longitude = Number(lonStr);
              } else {
                console.warn('经纬度格式错误（非数字）', latStr, lonStr);
              }
            } else {
              console.warn('locationInfo格式错误（需"纬度%#&经度"）', data.locationInfo);
            }
          } else {
            console.warn('locationInfo为空或无效', data.locationInfo);
          }

          // 赋值公司信息
          this.company = {
            ...this.company,
            name: data.companyName || '未知公司',
            scale: data.companySize || '',
            address: data.companyAddress || '暂无地址信息',
            image: data.companyImage || '/static/company-building.png',
            companyType: data.companyType || '',
            hrList: data.hrDOList || [],
            businessInfo: {
              '公司全称': data.companyName || '暂无数据',
              '法定代表人': data.legalRepresentative || '暂无数据',
              '成立日期': data.establishTime || '暂无数据',
              '统一社会信用代码': data.enterpriseCode || '暂无数据',
            },
            locationInfo: { latitude, longitude }
          };
		  console.log(this.isLocationValid)
        })
        .catch(err => {
          console.error('获取公司信息失败:', err);
          uni.showToast({ title: '加载失败', icon: 'none', duration: 2000 });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 核心：打开高德地图（唤起APP/提示下载）
    openGaodeMap() {
      const { latitude, longitude } = this.company.locationInfo;
      const companyName = this.company.name || '未知公司';

      // 拼接高德地图唤起链接（Scheme协议）
      const encodedName = encodeURIComponent(companyName);
      const gaodeScheme = `androidamap://viewMap?sourceApplication=公司详情页&poiname=${encodedName}&lat=${latitude}&lon=${longitude}&dev=0`;

      // 尝试唤起高德地图APP
      uni.openUrl({
        url: gaodeScheme,
        success: () => {
          console.log('成功唤起高德地图APP');
        },
        fail: () => {
          // 唤起失败：仅提示下载（不跳转应用商店）
          uni.showModal({
            title: '提示',
            content: '未检测到高德地图APP，请手动前往手机应用商店搜索"高德地图"下载后重试',
            confirmText: '知道了',
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                // 点击确认关闭弹窗
              }
            }
          });
        }
      });
    }
  }
}
</script>

<style scoped>
/* 页面基础样式 */
.company-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 24rpx; /* 移除底部操作栏后，减少底部留白 */
}

/* 导航栏样式 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.back-btn-hover {
  background-color: #f5f5f5;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.nav-right {
  width: 60rpx; /* 与返回按钮宽度一致，保证标题居中 */
}

/* 公司头部信息卡片 */
.company-header-card {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 24rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.company-header-content {
  display: flex;
  align-items: flex-start;
}

.company-logo {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  background-color: #f5f5f5;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.company-basic-info {
  flex: 1;
}

.company-name {
  font-size: 38rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.3;
  margin-bottom: 14rpx;
  display: block;
}

.company-meta {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
  flex-wrap: wrap;
}

.meta-item {
  font-size: 26rpx;
  color: #666;
  padding: 4rpx 0;
}

.meta-divider {
  color: #ccc;
  margin: 0 10rpx;
}

/* 地址与导航按钮样式 */
.company-address-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap; /* 适配小屏幕换行 */
}

.address-icon {
  margin-right: 8rpx;
  margin-top: 4rpx;
}

.company-address {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  word-break: break-all;
  flex: 1; /* 地址占满剩余空间，按钮居右 */
}

.navigate-btn {
  display: flex;
  align-items: center;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 40rpx;
  padding: 8rpx 20rpx;
  margin-left: 16rpx;
  cursor: pointer;
}

.navigate-btn-hover {
  background-color: #e6f2ff; /* 点击反馈 */
}

.navigate-text {
  font-size: 24rpx;
  margin-left: 8rpx;
}

/* 信息卡片通用样式 */
.info-card {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 0 24rpx 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
}

.card-content {
  padding: 30rpx;
}

/* 人事列表样式 */
.hr-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.hr-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
}

.hr-item:last-child {
  border-bottom: none;
}

.hr-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
  margin-right: 24rpx;
}

.hr-info {
  flex: 1;
}

.hr-name {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 6rpx;
  display: block;
}

.hr-position {
  font-size: 24rpx;
  color: #666;
}

/* 工商信息样式 */
.business-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24rpx 16rpx;
}

.business-info-item {
  display: flex;
  flex-direction: column;
  padding: 12rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
}

.business-info-item:nth-last-child(1),
.business-info-item:nth-last-child(2) {
  border-bottom: none;
}

.info-label {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 6rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  line-height: 1.4;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  color: #ccc;
}

.empty-text {
  font-size: 28rpx;
  margin-top: 16rpx;
}

/* 适配小屏幕 */
@media (max-width: 320px) {
  .business-info-grid {
    grid-template-columns: 1fr;
  }
  
  .hr-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .navigate-btn {
    margin-left: 0;
    margin-top: 12rpx;
    align-self: flex-start;
  }
}
</style>